#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : chart_bin_map.py
@Author  : Link
@Time    : 2022/12/11 12:35
@Mark    : 使用散点图做的bin map, 性能达不到要求, 可以考虑其他, 例如QCustomerChart, 或是直接用VBA->Excel.
"""
import math

from pyqtgraph import ScatterPlotItem

from chart_core.chart_pyqtgraph.ui_components.chart_visual_map import VisualMapChart
from common.data_class_interface.for_analysis_stdf import STDF_HEAD, PRR_HEAD
from common.li import FutureLi as Li


class BinMapChart(VisualMapChart):
    """
    继承VisualMapChart的架子
    不加入limit, 最小单元是GROUP, 不通过SITE去分组
    不太好用
    """

    def __init__(self, li: Li):
        super(BinMapChart, self).__init__(li)
        self.c = self.c.getLookupTable(alpha=True)

    def set_data(self, key: int):
        """
        简单点
        key: 1->HardBin, 2->SoftBin, 3->No
        """
        if self.li is None:
            raise Exception("first set li")
        self.key = key
        self.init_coord()

    def set_front_chart(self):
        """
        pxMode 将散点图框在了一起, 所以这个模式下一定要让图像生成了一次后就不能再动了
        """
        if self.li.to_chart_csv_data.chart_df is None:
            data_df = self.li.to_chart_csv_data.df
        else:
            data_df = self.li.to_chart_csv_data.chart_df
        if data_df is None:
            return
        map_group = data_df.groupby(STDF_HEAD.GROUP)
        self.pw.clear()
        if len(map_group) > 25:
            print("选取的Mapping数据过多了")
            return
        row = math.ceil(math.sqrt(len(map_group)))
        _min, _max = data_df[self.key].min(), data_df[self.key].max()
        diff = _max - _min
        if diff <= 0:
            self.label.setText("无有效数据")
            return
        for index, (key, df) in enumerate(map_group):
            t_row, t_col = divmod(index, row)
            plot_item = self.pw.addPlot(t_row, t_col, 1, 1, title=key)
            plot_item.getViewBox().invertY(True)
            plot_item.addLegend()
            plot_item.setMouseEnabled(x=False, y=False)

            bin_groups = df.groupby(PRR_HEAD.HARD_BIN)
            color_square_nm = math.ceil(pow(len(bin_groups), 0.5))
            color_split_nm = 512 / 2 ** color_square_nm
            color_list = self.c[::int(color_split_nm)]

            if self.key == 1:
                for i, (_bin, _df) in enumerate(bin_groups):
                    scatter = ScatterPlotItem(pxMode=False, )
                    scatter.addPoints(
                        _df.X_COORD.to_numpy(), _df.Y_COORD.to_numpy(),
                        size=1, symbol="s", name="HBIN:{}({})".format(_bin, len(_df)), brush=tuple(color_list[i])
                    )
                    plot_item.addItem(scatter)
